package ltd.nullpointer.frontend.web.controller.api;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.boot2.core.HlAssert;
import com.boot2.core.utils.FileUtil;
import com.boot2.core.utils.StringUtils;
import com.boot2.core.utils.ZipUtil;
import com.boot2.core.vo.Response;
import com.boot2.core.web.validator.FileUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.apachecommons.CommonsLog;
import ltd.nullpointer.frontend.model.dto.up.FormulaDto;
import ltd.nullpointer.frontend.service.NpAtrributeKvService;
import ltd.nullpointer.frontend.web.controller.ApiBaseController;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhangweilin
 * @date 2019/5/7 14:38
 * @Description: 设备动态属性
 */
@Api(tags = "设备动态属性")
@RestController
@RequestMapping("/user/attributeKv")
@CommonsLog
public class AttributeKvController extends ApiBaseController {

    @Autowired
    NpAtrributeKvService npAtrributeKvService;

    /**
     *
     * @param sensorNo
     * @return
     */
    @ApiOperation(value = "获取指定设备所有的属性值")
    @GetMapping(value = "/turnOn/{sensorNo}")
    public Response<Map<String, Double>> getAllAttributeKv(@PathVariable String sensorNo) {
        Map<String, Double> allAttributeKvList = npAtrributeKvService.selectAllAttributeKv(sensorNo);
        return success(allAttributeKvList);
    }

    @ApiOperation(value = "测试生成动态列")
    @GetMapping(value = "/testGenColumn")
    public Response<String> testGenColumn(String sensorNo) {
        sensorNo = StringUtils.isEmpty(sensorNo) ? null : sensorNo;
        int count = npAtrributeKvService.genColumns(sensorNo);
        return success("成功为"+count+"个设备生成公式字段");
    }


    @ApiOperation(value = "设置公式")
    @PostMapping(value = "/setFormula")
    public Response<Void> setFormula(@Valid FormulaDto formulaDto, BindingResult bindingResult) {
         npAtrributeKvService.updateSetFormula(formulaDto);
        return success();
    }

    @ApiOperation(value = "批量导入修正公式(xls,xlsx,zip格式)")
    @PostMapping("/uploadFormula")
    @FileUpload(suffixs = "xls,xlsx,zip", maxSize = 10 * 1000 * 1000, maxNum = 1)
    public Response<Void> uploadXlsx(@ApiParam(value = "多文件上传", required = true) MultipartFile file) throws IOException {
        HlAssert.notNull(file, "文件无效");
        String originalFilename = file.getOriginalFilename();
        File file0 = new File(originalFilename);
        FileUtils.copyInputStreamToFile(file.getInputStream(), file0);

        //如果上传的是zip
        if (originalFilename.endsWith(".zip")) {
            File file2 = ZipUtil.unZip(file0.getAbsolutePath());
//            System.out.println("file2 = " + file2);
            ArrayList<File> fileList = FileUtil.getAllFile(file2);
            log.info("上传了压缩文件，解压后共【"+fileList.size()+"】个excel文件");
            for (File file1 : fileList) {
                handSensorData(file1);
            }
        }else{
            handSensorData(file0);
        }
        return success();
    }

    private void handSensorData(File file1) throws FileNotFoundException {
        List<Object> dataList = EasyExcelFactory.read(new BufferedInputStream(new FileInputStream(file1)), new Sheet(1, 1));
        log.info("解析文件:" + file1 + ", 共【" + dataList.size() + "】条数据");
        for (Object object : dataList) {
            List<Object> objectList = (List<Object>) object;
            String sensorNo = (String) objectList.get(0);
            if (sensorNo == null) continue;
            FormulaDto formulaDto = new FormulaDto();
            formulaDto.setSensorNo(sensorNo);
            Double initialValue = objectList.get(1) == null ? 0 : Double.parseDouble(String.valueOf(objectList.get(1)));
            formulaDto.setInitial_value(initialValue);
            Double height = objectList.get(2) == null ? 0 : Double.parseDouble(String.valueOf(objectList.get(2)));
            formulaDto.setHeight(height);
            Double depth = objectList.get(3) == null ? 0 : Double.parseDouble(String.valueOf(objectList.get(3)));
            formulaDto.setDepth(depth);
            Double ratio = objectList.get(4) == null ? 1 : Double.parseDouble(String.valueOf(objectList.get(4)));
            formulaDto.setRatio(ratio);
            Double controlFlag = objectList.get(5) == null ? 0 : Double.parseDouble(String.valueOf(objectList.get(5)));
            formulaDto.setControl_flag(controlFlag);
            Map<String, Double> attributeKvList = npAtrributeKvService.selectAllAttributeKv(sensorNo);
            if (attributeKvList == null || !attributeKvList.containsKey("control_flag")) {
                npAtrributeKvService.genColumns(sensorNo);
            }
            npAtrributeKvService.updateSetFormula(formulaDto);
        }
    }

}
